package com.example.wxchatdemo.Files;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class putfiles {
    private Socket socket;
    private String address="100.2.193.182";
    private InputStream is;
    private OutputStream os;

    public String getFile_name() {
        return File_name;
    }

    public void setFile_name(String file_name) {
        File_name = file_name;
    }

    public putfiles() {
    }

    public putfiles(String file_name) {
        File_name = file_name;
    }

    private  String File_name;
    public void putfiles_one() throws IOException {
        try{
            socket=new Socket(address,8089);
            if (socket!=null){
                is = socket.getInputStream();
                os = socket.getOutputStream();
            }
            System.out.println("输出socket"+socket.toString());

        }catch (Exception E){
            System.out.println("连接异常-38-putfile");
        }
        //发送文件名

       // String filename="ac.jpg-get";
        String filename=getFile_name()+"-get";
        byte[] bytes1 = filename.getBytes();
        os.write(bytes1);
        String[] split=filename.split("-");
            System.out.println("启动接收文件函数");
            getFiles(socket,split[0]);

        if (socket!=null){
            socket.close();
        }

    }
    //接收文件
    public void  getFiles(Socket socket,String FilePath) throws IOException {
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        while (true) {
            byte[] bytes = new byte[4096];
            int x = 0;
            int y = 1;
            FileOutputStream fileOutputStream = null;
            File file;
            while ((x = is.read(bytes)) != -1) {
                if (y == 1) {
                    //获取文件名
                    System.out.println("文件名" + new String(bytes, 0, x));
                    file = new File("/storage/emulated/0/AppFiles/" + FilePath);
                    fileOutputStream = new FileOutputStream(file);
                    System.out.println("文件名为" + new String(bytes, 0, x));
                    fileOutputStream.write(bytes,0,x);
                    y++;
                    continue;
                }
                //写入文件
                fileOutputStream.write(bytes, 0, x);
                System.out.println("循环了" + y + "次");
                y++;
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }

            System.out.println("文件接收完成");
            break;
        }


        if (socket != null) {

            socket.close();

        }
    }
}
